package class02;

import java.util.Stack;

/**
 * @author zhangchaoliang
 * create 2022
 */
public class GetMinStack2 {
    public static class MyStack1{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack1(){
            this.stackData=new Stack<Integer>();
            this.stackMin=new Stack<Integer>();
        }

        public int getmin(){
            if (stackMin.isEmpty()){
                throw new RuntimeException("You stack is empty.");
            }
            return stackMin.peek();
        }

        public void push(int newNum){
            if (stackMin.isEmpty()){
                stackMin.push(newNum);
            }else if (newNum<=getmin()){
                stackMin.push(newNum);
            }

            stackData.push(newNum);
        }

        public int pop(){
            if (stackMin.isEmpty()){
                throw new RuntimeException("You stack is empty.");
            }
            int value = stackData.pop();
            if (value==getmin()){
                stackMin.pop();
            }
            return value;
        }
    }

    public static class MyStack2{
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack2(){
            this.stackData=new Stack<Integer>();
            this.stackMin=new Stack<Integer>();
        }

        public int getmin(){
            if (stackMin.isEmpty()){
                throw new RuntimeException("You stack is empty.");
            }
            return stackMin.peek();
        }

        public void push(int newNum){
            if (stackMin.isEmpty()){
                stackMin.push(newNum);
            }else if (newNum<getmin()){
                stackMin.push(newNum);
            }else {
                stackMin.push(getmin());
            }
            stackData.push(newNum);
        }

        public int pop(){
            if (stackMin.isEmpty()){
                throw new RuntimeException("You stack is empty.");
            }
            stackMin.pop();
            return stackData.pop();
        }
    }
    public static void main(String[] args) {
        MyStack1 stack1 = new MyStack1();
        stack1.push(3);
        System.out.println(stack1.getmin());
        stack1.push(4);
        System.out.println(stack1.getmin());
        stack1.push(1);
        System.out.println(stack1.getmin());
        System.out.println(stack1.pop());
        System.out.println(stack1.getmin());

        System.out.println("=============");

        MyStack1 stack2 = new MyStack1();
        stack2.push(3);
        System.out.println(stack2.getmin());
        stack2.push(4);
        System.out.println(stack2.getmin());
        stack2.push(1);
        System.out.println(stack2.getmin());
        System.out.println(stack2.pop());
        System.out.println(stack2.getmin());
    }

}
